package org.example;

import org.junit.jupiter.api.Test;

import java.sql.*;

public class test {

    @Test
    public void testJdbc() throws Exception {
        // 获取连接
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db03", "root", "1234");
        //方式一:创建预编译的PreparedStatement对象
        PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM user WHERE username = ? AND password = ?");
        // 设置参数
        pstmt.setString(1, "daqiao"); // 第一个问号对应的参数
        pstmt.setString(2, "123456"); // 第二个问号对应的参数
        // 执行查询
        ResultSet rs1 = pstmt.executeQuery();

        //方式二:
        Statement stmt = conn.createStatement();
        ResultSet rs=stmt.executeQuery("select * from user where username='daqiao' and password='123456'");

        // 处理结果集
        while (rs.next()) {
            int id = rs.getInt("id");
            String uName = rs.getString("username");
            String pwd = rs.getString("password");
            String name = rs.getString("name");
            int age = rs.getInt("age");
            System.out.println("ID: " + id + ", Username: " + uName + ", Password: " + pwd + ", Name: " + name + ", Age: " + age);
        }
        pstmt.close();
        rs.close();
        stmt.close();
        conn.close();
    }
    @Test
    public void testUpdate() throws Exception {
        Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/db03", "root", "1234");
        String sql = "update user set username='daqiao', password='12349111' where id=1";
        Statement stmt = con.createStatement();
        int count=stmt.executeUpdate(sql);
        System.out.println(count);
        stmt.close();
        con.close();
    }
}
